from typing import Optional

from langchain_core.runnables import RunnableConfig
from pydantic import BaseModel
from .base import BaseNodes, tool_node
from ...models.graph import GraphState
from ...utils.str import unescape_html


class CommandSchema(BaseModel):
    command: str
    requires_approval: bool = False
    is_resident: Optional[bool]


class CommandNodes(BaseNodes):
    @tool_node(args_schema=CommandSchema, args_parser={"command": unescape_html})
    def execute_command(self, state: GraphState, *, config: Optional[RunnableConfig] = None):
        """
        执行系统CLI命令。用于完成任务中的系统操作，优先使用CLI命令而非脚本。
        参数:
        - command: (必填) 要执行的CLI命令，需适配当前操作系统
        - requires_approval: (必填) 是否需要用户批准。高风险操作(安装/卸载、删除/覆盖文件、系统配置)设为true，安全操作设为false
        - is_resident: (可选) 是否为持续运行进程(如npm run dev)
        用法:
        <execute_command>
        <command>Your command here</command>
        <requires_approval>true or false</requires_approval>
        <is_resident>true or false</is_resident>
        </execute_command>
        示例:
        <execute_command>
        <command>npm run dev</command>
        <requires_approval>false</requires_approval>
        <is_resident>true</is_resident>
        </execute_command>
        """
        return self.wait_human_feedback()
